const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')
const router = new Router()
app.use(bodyParser())
let mysql = require('mysql');
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'a123',
    password: '123456',
    database: 'mysql1'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    if (error) throw error;
    console.log('The solution is: ', results[0].solution);
});
//文件上传
router.post("/upLoad",async(ctx,next)=>{
    ctx.body="hello world"
})
//注册
router.post('/register', async (ctx, next) => {
    try {
        const { username, password, phone } = ctx.request.body;
        let res = await new Promise((resolve, reject) => {
            connection.query("select * from user where username=?", username, (error, results) => {
                if (error) reject(error)
                resolve(results)
            })
        })
        if (res.length === 0) {
            connection.query("insert into user set ?", { username, password, phone }, (error) => {
                if (error) reject(error)
                resolve()
            })
            ctx.body = {
                code: 1,
                msg: '恭喜您,注册成功'
            }
        } else {
            ctx.body = {
                code: 2,
                msg: '不好意思,用户已经存在'
            }
        }

    } catch (error) {
        ctx.body = {
            code: 0,
            msg: error
        }
    }
})
//登录
router.post('/login', async (ctx, next) => {
    try {
        const { username, password } = ctx.request.body
        console.log(username)
        let res = await new Promise((resolve, reject) => {
            connection.query("select * from user where username=? and password=?", [username, password], (error, results) => {
                if (error) reject(error)
                resolve(results)
            })
        })
        if (res.length) {
            ctx.body = {
                code: 1,
                msg: "恭喜您登录成功"
            }
        } else {
            ctx.body = {
                code: 2,
                msg: "用户名或密码错误"
            }
        }
    } catch (error) {
        ctx.body = {
            code: 0,
            msg: error
        }
    }
})

app.use(router.routes())
    .use(router.allowedMethods)
app.listen(4000, () => {
    console.log(`run as http://localhost:4000`)
})